<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Preview</title>
    <script src="./docx-preview/index.umd.js"></script>
    <link rel="stylesheet" href="./docx-preview/index.css">
    <script src="./pdf-preview/index.umd.js"></script>
    <script src="./excel-preview/index.umd.js"></script>
    <link rel="stylesheet" href="./excel-preview/index.css">
    <style>
        body {
            height: 100vh;
        }

        #app {
            height: 100vh;
        }

        #container {
            transform-origin: left top;
        }

        #download {
            display: none;
            position: fixed;
            width: 100px;
            height: 30px;
            left: 50%;
            margin-left: -50px;
            text-align: center;
            bottom: 10px;
            text-decoration: none;
            z-index: 9;

        }

        .padding {
            height: 100px;
        }

        #preview-img {
            display: none;
            max-width: 100%;
            margin: 0 auto;
        }

        #preview-txt {
            display: none;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        #float-box {
            position: fixed;
            bottom: 10px;
            right: 10px;
            z-index: 9;
            opacity: 0.8;
        }

        #float-box button {
            margin-bottom: 10px;
        }

        #scale-big {
            display: none;
        }

        #scale-small {
            display: none;
        }
    </style>
</head>

<body>
    <div id="container">
        <div id="app"></div>
        <img id="preview-img" src="" />
        <div id="preview-txt"></div>
        <div class="padding"></div>
    </div>
    <a id="download" href>下载文件</a>
    <div id="float-box">
        <button id="scale-big" onclick="scaleBig()">放大</button>
        <button id="scale-small" onclick="scaleSmall()">缩小</button>
    </div>


    <script>
        /** 
         * demo /index.html?fileUrl=https%3A%2F%2F501351981.github.io%2Fvue-office%2Fexamples%2Fdist%2Fstatic%2Ftest-files%2Ftest.docx
        * 路由参数
        * 
        * fileType: 文件类型，可选值：docx, pdf, xlsx, img, txt, json 非必传，自动根据后缀获取
        * fileUrl: 文件url
        * isDownload: 是否可下载,显示下载按钮。 可选值：1 0，非必传 
        * 
        */


        // 参考文档 https://www.npmjs.com/package/@js-preview/docx?activeTab=readme
        var containerDom = document.getElementById('container')
        var appDom = document.getElementById('app')
        var imgDom = document.getElementById('preview-img')
        var textDom = document.getElementById('preview-txt')


        var fileUrl = getQueryVariable('fileUrl');
        if (fileUrl) fileUrl = decodeURIComponent(fileUrl);
        var fileType = getQueryVariable('fileType') || '';
        if (fileType) mode = decodeURIComponent(fileType);
        var isDownload = getQueryVariable('isDownload');
        if (isDownload) isDownload = decodeURIComponent(isDownload) === '1';
        var scale = getQueryVariable('scale');
        if (scale) scale = decodeURIComponent(scale) === '1';

        console.log({
            fileUrl,
            fileType,
            isDownload, scale
        })


        if (!fileUrl) {
            appDom.innerText = '缺少fileUrl参数'
            throw new Error('缺少fileUrl参数');
        }

        if (!fileType) {
            let lowerFileUrl = fileUrl.toLowerCase();
            if (lowerFileUrl.includes('.docx')) {
                fileType = 'docx';
            } else if (lowerFileUrl.includes('.pdf')) {
                fileType = 'pdf';
            } else if (lowerFileUrl.includes('.xlsx')) {
                fileType = 'excel';
            } else if (strIncludeArray(lowerFileUrl, ['.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp', '.svg', '.tiff'])) {
                fileType = 'img';
            } else if (strIncludeArray(lowerFileUrl, ['.txt', '.json'])) {
                fileType = 'txt';
            }
        }

        console.log('fileType', fileType)

        if (isDownload) {
            document.getElementById("download").style.display = "block";
            document.getElementById("download").href = fileUrl
        }
        if (scale) {
            document.getElementById("scale-big").style.display = "block";
            document.getElementById("scale-small").style.display = "block";
        }



        if (fileType === 'docx') {
            const myDocxPreviewer = jsPreviewDocx.init(appDom);
            myDocxPreviewer.preview(fileUrl).then(res => {
                console.log('预览完成');
            }).catch(e => {
                console.log('预览失败', e);
                appDom.innerText = '预览失败' + '  ' + fileUrl + ' ' + JSON.stringify(e)
            })

        } else if (fileType === 'pdf') {
            const myPdfPreviewer = jsPreviewPdf.init(appDom);
            myPdfPreviewer.preview(fileUrl).then(res => {
                console.log('预览完成');
            }).catch(e => {
                console.log('预览失败', e);
                appDom.innerText = '预览失败' + '  ' + fileUrl + ' ' + JSON.stringify(e)
            })
        } else if (fileType === 'excel') {
            const myExcelPreviewer = jsPreviewExcel.init(appDom);
            myExcelPreviewer.preview(fileUrl).then(res => {
                console.log('预览完成');
            }).catch(e => {
                console.log('预览失败', e);
                appDom.innerText = '预览失败' + '  ' + fileUrl + ' ' + JSON.stringify(e)
            })
        } else if (fileType === 'img') {
            imgDom.src = fileUrl
            imgDom.style.display = "block";
        } else if (fileType === 'txt' || fileType === 'json') {
            requestText(fileUrl, function (res) {
                textDom.innerText = res;
                textDom.style.display = "block";
            })
        } else {
            appDom.innerText = '暂不支持该文件类型: ' + fileUrl
        }

        /**　获取路由参数 */
        function getQueryVariable(variable) {
            var query = window.location.search.substring(1);
            var vars = query.split('&');
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split('=');
                if (pair[0] == variable) {
                    return pair[1];
                }
            }
            return false;
        }

        function requestText(url, callback) {
            var xhttp = new XMLHttpRequest();
            xhttp.open("GET", url, true);
            xhttp.onreadystatechange = function () {
                if (this.readyState == 4) {
                    if (this.status == 200) { callback(this.responseText) }
                    else {
                        callback('加载失败 status: ' + xhttp.status + ' ' + url);
                    }

                }
            };
            xhttp.send();
        }

        var scaleNum = 1;
        function scaleBig() {
            scaleNum += 0.1;
            containerDom.style.transform = "scale(" + scaleNum + ")";
        }
        function scaleSmall() {
            scaleNum -= 0.1;
            containerDom.style.transform = "scale(" + scaleNum + ")";
        }
        function strIncludeArray(str, array) {
            for (let i = 0; i < array.length; i++) {
                if (str.includes(array[i])) {
                    return true
                }
            }
            return false
        }
    </script>

</body>

</html>